import { FC, Suspense } from 'react'
import { BrowserRouter, HashRouter, Navigate, Routes, Route } from 'react-router-dom'
import { RouterItem, RouterList } from './type'

type Props = {
  routes: RouterList;
  mode?: 'history' | 'hash';
}

const App: FC<Props> = ({ routes, mode }) => {
  const RenderRouter = (arr: RouterList) => {
    return arr.map((item: RouterItem, index: number) => {
      return (
        <Route key={index} path={item.path} element={item.element ? <item.element /> : <Navigate to={item.to as string} />}>
          {
            item.children && RenderRouter(item.children)
          }
        </Route>
      )
    })
  }

  return (
    <Suspense fallback={<div>...路由加载</div>}>
      {
        mode === 'history' ?
          <BrowserRouter>
            <Routes>
              {
                RenderRouter(routes)
              }
            </Routes>
          </BrowserRouter>
          :
          <HashRouter>
            <Routes>
              {
                RenderRouter(routes)
              }
            </Routes>
          </HashRouter>

      }
    </Suspense>
  )
}

export default App